package com.aiti.lulian.components.wx;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.lulian.components.wx.domain.SendCardExchange;
import com.aiti.lulian.dto.SendCardExchangeDto;
import com.aiti.lulian.utils.WxPublicPlatformTokenUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信服务号推送信息组件
 * <p>
 *     因为需要推送小程序那边的信息到服务号，<br />
 *     在进行开发之前需要将服务号和小程序关联起来，这样这服务号和小程序的openId才会一致<br />
 *     {@link https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html}
 * </p>
 */
@Component
public class WxComponent {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Value("${wx.token}")
    private String token;

    private final RestTemplate restTemplate;

    private final StringRedisTemplate redisTemplate;

    private final String SEND_CARD_EXCHANGE_TIP = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
    private final String SEND_CUSTOM_MESSAGE_TIP = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";
    @Autowired
    private WxPublicPlatformTokenUtils wxPublicPlatformTokenUtils;
    public WxComponent(RestTemplate restTemplate,StringRedisTemplate redisTemplate) {
        this.restTemplate = restTemplate;
        this.redisTemplate = redisTemplate;
    }

    public boolean sendCardAccessTip(String userId, String userOpenId,String userName,String position,
                                     String enterpriseName,String baseId,String phonenumber){
//        if(StringUtils.isBlank(userOpenId) || StringUtils.isBlank(userName) ){
        if(StringUtils.isBlank(userOpenId)){
            return false;
        }

        StringBuilder xcxPath = new StringBuilder("pages/Preview/Preview?source=index");
        if((StringUtils.equals(baseId,"isNotLogin") || StringUtils.isBlank(baseId) || StringUtils.isBlank(phonenumber)) && StrUtil.isNotBlank(userId)) {
            xcxPath = new StringBuilder("subpackages/pages/myCardData/myCardData?userId=" + userId + "&visitor=1");
        }else{
            if(StringUtils.isNotBlank(baseId) && !StringUtils.equals(baseId,"isNotLogin")){
                xcxPath.append("&baseId=").append(baseId);
            }
            if(StringUtils.isNotBlank(phonenumber)){
                xcxPath.append("&phonenumber=").append(phonenumber);
            }
        }
        SendCardExchange build = SendCardExchange.builder()
                .touser(userOpenId)
                .templateId("KkHDB1jFpW6-uiWQBqR3nP7byP7kk8JSkeysFMe-pIg")
                .url("")
                .topcolor("#FF0000")
                .build();

        JSONObject userNameJsonObject = new JSONObject();
        userNameJsonObject.put("thing1", new HashMap<String, String>() {
            {put("value",StringUtils.isBlank(userName) ? "微信用户" : userName);}
            {put("color",StringUtils.isBlank(userName) ? "#ff3a68" : "#173177");}
        });

        JSONObject accessTimeJsonObject = new JSONObject();
        accessTimeJsonObject.put("time4", new HashMap<String, String>() {
            {put("value", DateUtil.now());}
            {put("color","#173177");}
        });

        JSONObject enterpriseNameJsonObject = new JSONObject();
        enterpriseNameJsonObject.put("thing3", new HashMap<String, String>() {
            {put("value", StringUtils.isNotBlank(enterpriseName) ? enterpriseName : "暂未填写");}
            {put("color","#173177");}
        });

        Map<String,Object> data = new HashMap<>();
        data.putAll(userNameJsonObject);
        data.putAll(accessTimeJsonObject);
        data.putAll(enterpriseNameJsonObject);
        build.setData(data);

        //加上小程序
        JSONObject xcxJsonObject = new JSONObject();
        xcxJsonObject.put("appid","wx7ca766313703d868");
        xcxJsonObject.put("pagepath",xcxPath);

        Map<String,Object> xiaoChengXuMap = new HashMap<>();
        xiaoChengXuMap.putAll(xcxJsonObject);
        build.setMiniprogram(xiaoChengXuMap);

        //获取出Token
        String token = wxPublicPlatformTokenUtils.getToken();
        if(StringUtils.isBlank(token)){
            throw new RuntimeException("获取Token失败");
        }
        String finalUrl = String.format(SEND_CARD_EXCHANGE_TIP, token);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(finalUrl, build, String.class);
        if(stringResponseEntity.getStatusCode().is2xxSuccessful()){
            String body = stringResponseEntity.getBody();
            JSONObject resultObject = JSONObject.parseObject(body);
            String o = (String)resultObject.get("errmsg");
            if(StringUtils.equals(o,"ok")){
                return true;
            }
        }
        return false;
    }

    /**
     * 发送名片交换请求提醒
     */
    public boolean sendCardExchangeRequest(SendCardExchangeDto dto) {
        SendCardExchange build = SendCardExchange.builder()
                .touser(dto.getToOpenId())
//                .templateId("33dEa7WrZTOSRjwxcJ0rc90ywUNx0IMMSV8B9voiRTo")
                .templateId("En2Rcz155DFDFWqbvyUg8VoCfOoZooKcRU2oZWk_5L4")
                .url("")
                .topcolor("#FF0000")
                .build();

        JSONObject userNameJsonObject = new JSONObject();
        userNameJsonObject.put("name1", new HashMap<String, String>() {
            {put("value",StringUtils.isBlank(dto.getUsername()) ? "对方暂无填写" : dto.getUsername());}
            {put("color","#173177");}
        });
        JSONObject positionJsonObject = new JSONObject();
        positionJsonObject.put("thing4", new HashMap<String, String>() {
            {put("value",StringUtils.isBlank(dto.getPosition()) ? "对方暂无填写" : dto.getPosition());}
            {put("color","#173177");}
        });
        JSONObject currentTimeJsonObject = new JSONObject();
        currentTimeJsonObject.put("thing3", new HashMap<String, String>() {
            {put("value",StringUtils.isBlank(dto.getEnterpriseName()) ? "对方暂无填写" : dto.getEnterpriseName());}
            {put("color","#173177");}
        });
        JSONObject enterpriseNameJsonObject = new JSONObject();
        enterpriseNameJsonObject.put("time8", new HashMap<String, String>() {
            {put("value",StringUtils.isBlank(dto.getCurrentTime()) ? "对方暂无填写" : dto.getCurrentTime());}
            {put("color","#173177");}
        });
        Map<String,Object> data = new HashMap<>();
        data.putAll(userNameJsonObject);
        data.putAll(positionJsonObject);
        data.putAll(currentTimeJsonObject);
        data.putAll(enterpriseNameJsonObject);
        build.setData(data);

        //获取出Token
        String token = wxPublicPlatformTokenUtils.getToken();;
        if(StringUtils.isBlank(token)){
            throw new RuntimeException("获取Token失败");
        }
        String finalUrl = String.format(SEND_CARD_EXCHANGE_TIP, token);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(finalUrl, build, String.class);
        if(stringResponseEntity.getStatusCode().is2xxSuccessful()){
            String body = stringResponseEntity.getBody();
            JSONObject resultObject = JSONObject.parseObject(body);
            String o = (String)resultObject.get("errmsg");
            if(StringUtils.equals(o,"ok")){
                return true;
            }
        }
        return false;
    }



}
